package controllers

import dao._
import implicits.Implicits._
import models.Tables._
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.FormTool
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import argonaut.Argonaut._
import argonaut.ArgonautShapeless._

/**
 * Created by Administrator on 2019/8/7
 */
class WechatMemberController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val wechatMemberDao: WechatMemberDao
) extends
  AbstractController(cc) {

  def add = Action.async { implicit request =>
    val data = FormTool.phoneForm.bindFromRequest().get
    val row = WechatMemberRow(data.phone, new DateTime())
    wechatMemberDao.insert(row).map { x =>
      Ok(Json.toJson("success!"))
    }
  }

  def all = Action.async { implicit request =>
    wechatMemberDao.selectAll.map { x =>
      val array =x.map(_.asJson)
      Ok(array.asJson)
    }
  }

  def delete = Action.async { implicit request =>
    val data = FormTool.phoneForm.bindFromRequest().get
    wechatMemberDao.deleteByPhone(data.phone).map { x =>
      Ok(Json.obj("result"->"success"))
    }
  }

  def phoneCheck = Action.async { implicit request =>
    val data = FormTool.phoneForm.bindFromRequest.get
    val bsF = Future.sequence(
      List(
        wechatMemberDao.phoneExist(data.phone)
      )
    )
    bsF.zip(accountDao.selectById1).map { case (bs, admin) =>
      if (bs.exists(x => x)) {
        Ok(Json.obj("valid" -> false))
      } else {
        Ok(Json.obj("valid" -> true))
      }
    }
  }


}
